<template>
	<view class='map'>
		<view id='map'></view>
		<!-- 搜索位置 -->
		<view class='search_content dFlex jBetween_aCenter'>
			<input class='ipt' type="text" :placeholder='$t("map.placeholder")' v-model='keyword'
				placeholder-style="font-size:14px;">
			<view class='searchBtn' @click='searchKw'>{{$t("map.btn")}}</view>
		</view>
		<!-- 地址列表 -->
		<u-popup :show="addDialog">
			<view class='title dFlex jBetween_aCenter'>
				<text></text>
				<text>{{$t("pages.map")}}</text>
				<text><u-icon name="close" @click='addDialog = false'></u-icon></text>
			</view>
			<view class='addList'>
				<view :class='["addOne",subAddInfo == item.formatted_address ? "active":""]'
					@click='chooseAddress(item)' v-for="(item,index) in addressList" :key='index'>
					{{item.formatted_address}}
				</view>
			</view>
			<view class='btns'>
				<view class='saveBtn' @click='saveAddInfo'>{{$t("map.btn2")}}</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import {
		Loader
	} from "@googlemaps/js-api-loader";
	const loader = new Loader({
		apiKey: "AIzaSyCCoa8Cc7V0l9iT2ZdfHMXOjxhdCXE7GnA",
		version: "weekly",
		libraries: ["places"]
	});
	// 输入框模糊查询
	let searchBox = null;
	// 搜索地点和检索地点详细信息
	let service = null;
	// 对请求进行地理编码
	let geocoder = null;
	export default {
		data() {
			return {
				id: '', //编辑时的地址
				keyword: '',
				geocoder: '',
				lat: '',
				lng: '',
				map: null,
				subAddInfo: '',
				addLat: '',
				addLng: "",
				// 地址选择列表
				addDialog: false,
				addressList: [],
				cart_ids: ''
			};
		},
		onLoad(e) {
			this.cart_ids = e.cart_ids ?? '';
			this.id = e.id ? e.id : '';
			this.lat = e.lat ? Number(e.lat) : '';
			this.lng = e.lng ? Number(e.lng) : "";
			this.subAddInfo = e.area ? e.area : '';
		},
		mounted() {
			uni.setNavigationBarTitle({
				title: this.$t('pages.map'),
			})

			uni.getLocation({
				type: 'wgs84',
				altitude: true,
				geocode: false,
				success: (location) => {
					if (!this.id) {
						console.log('经纬度', location);
						this.lat = Number(location.latitude);
						this.lng = Number(location.longitude);
					}
					// this.initMap();
				},
				fail: (err) => {
					console.log(err);
				}
			})
		},
		methods: {
			// 选择地址
			chooseAddress(line) {
				this.subAddInfo = line.formatted_address;
				this.addLat = line.geometry.location.lat();
				this.addLng = line.geometry.location.lng();
			},
			// 保存地址内容
			saveAddInfo() {
				if (!this.subAddInfo) {
					uni.showToast({
						title: this.$t("map.toast1"),
						icon: "none"
					})
					return;
				}
				if (!this.id) {
					uni.navigateTo({
						url: './editAdd?content=' + this.subAddInfo + '&lat=' + this.addLat + '&lng=' + this
							.addLng + '&cart_ids=' + this.cart_ids,
					})
				} else {
					var pages = getCurrentPages();
					var lastPage = pages[pages.length - 2];
					lastPage.$vm.addInfo.area = this.subAddInfo;
					lastPage.$vm.addInfo.latitude = this.addLat;
					lastPage.$vm.addInfo.longitude = this.addLng;
					uni.navigateBack({
						delta: 1
					})
				}
			},
			// 获取点击的位置
			getAddress(location) {
				// 使用地理编码器根据坐标获取地址
				this.geocoder.geocode({
					location: location,
					region: 'FR',
				}, (results, status) => {
					console.log('解析地址', results);
					console.log('状态', status);
					if (status === 'OK') {
						if (results.length) {
							// this.addressList = results.map(item=>item.formatted_address);
							this.addressList = results;
							this.addDialog = true;
						} else {
							uni.showToast({
								title: this.$t("map.toast2"),
								icon: "none"
							})
						}
					} else {
						uni.showToast({
							title: this.$t("map.toast3"),
							icon: "none"
						})
					}
				});
			},
			// 关键字搜索
			searchKw() {
				if (this.keyword) {
					var keyword = this.keyword;
					console.log('搜索的关键字', keyword);
					// 使用地理编码器转换地址为经纬度
					this.geocoder.geocode({
						address: keyword
					}, (results, status) => {
						console.log('搜索结果', results);
						console.log('状态', status);
						if (status === 'OK') {
							// 获取第一个搜索结果
							const location = results[0].geometry.location;
							// 在地图上标记位置
							new google.maps.Marker({
								position: location,
								map: this.map
							});
							// 设置地图中心
							this.map.setCenter(location);
						} else {
							alert('无法找到该地址：' + status);
						}
					});
				}
			},
			initMap() {
				loader.load().then((google) => {
						this.map = new google.maps.Map(
							document.getElementById("map"), {
								// 地图打开时的中心点位，根据自己需求自行更改
								center: {
									/* lat: 1.3553976, 
									lng: 103.867750, */
									lat: this.lat,
									lng: this.lng,
								},
								gestureHandling: "greedy",
								// 地图缩放参数
								zoom: 12,
								// 最大缩放参数
								maxZoom: 18,
								// 最小缩放参数
								minZoom: 4,
								// 禁用默认UI
								disableDefaultUI: true
							}
						);
						const marker = new google.maps.Marker({
							position: {
								lat: this.lat,
								lng: this.lng
							},
							map: this.map,
							title: 'I am here！'
						});
						// 初始化地理编码器
						this.geocoder = new google.maps.Geocoder();
						// 添加点击事件监听器
						this.map.addListener('click', (event) => {
							this.getAddress(event.latLng);
						});
					})
					.catch((e) => {
						console.log(e)
					})
			},
		}
	}
</script>

<style lang="scss">
	.title {
		width: 100%;
		text-align: center;
		padding: 10px 12px;
		box-sizing: border-box;
		border-bottom: 1px solid rgba(0, 0, 0, 0.1);
	}

	.btns {
		.saveBtn {
			width: 100%;
			background: $main;
			color: white;
			text-align: center;
			border-radius: 4px;
			padding: 10px 0;
		}

		width: 100%;
		padding: 12px;
		box-sizing:border-box;
	}

	.addList {
		.addOne {
			width: 100%;
			padding: 10px;
			box-sizing: border-box;
			box-shadow: 0px 0px 5px rgba(0, 0, 0, 0.3);
			border-radius: 4px;
			margin-bottom: 12px;
			border: 2px solid transparent;
		}

		.active {
			border-color: $main;
		}

		width: 100%;
		height: 50vh;
		overflow: auto;
		padding: 12px;
		box-sizing: border-box;
	}

	.search_content {
		.ipt {
			flex: 1;
		}

		.searchBtn {
			width: max-content;
			padding: 5px 10px;
			color: white;
			background: $main;
			font-size: 14px;
			margin-left: 12px;
			border-radius: 4px;
		}

		width:calc(100% - 24px);
		position:absolute;
		top:12px;
		left:12px;
		border-radius: 4px;
		background: white;
		padding:8px;
		box-sizing:border-box;
	}

	#map {
		width: 100%;
		height: 100vh;
	}

	.map {
		position: relative;
	}

	page {
		background: white;
	}
</style>